package com.cn.kabalifeuser.ui.integral.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.baidu.mapapi.map.offline.MKOfflineMapListener;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.cn.kabalifeuser.R;
import com.cn.kabalifeuser.base.IBaseActivity;
import com.cn.kabalifeuser.config.CustomRefreshListener;
import com.cn.kabalifeuser.config.LoginHelper;
import com.cn.kabalifeuser.config.RefreshHelper;
import com.cn.kabalifeuser.ui.integral.bean.CartCheckBean;
import com.cn.kabalifeuser.ui.integral.bean.CartListBean;
import com.cn.kabalifeuser.ui.integral.bean.OrderPlaceBean;
import com.cn.kabalifeuser.ui.integral.bean.OrderSetBean;
import com.cn.kabalifeuser.ui.login.bean.MsgBean;
import com.cn.kabalifeuser.utils.GlideUtil;
import com.cn.kabalifeuser.utils.LoggerUtils;
import com.cn.kabalifeuser.utils.RxToast;
import com.cn.kabalifeuser.utils.StringUtil;
import com.cn.kabalifeuser.utils.TimeUtils;
import com.flyco.roundview.RoundTextView;
import com.kongzue.dialog.v2.SelectDialog;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;

import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by 晓林 on 2020/9/11.
 * function: 购物车
 */
public class CartListActivity extends IBaseActivity<CartListView, CartListPresenter> implements CartListView {
    DecimalFormat df = new DecimalFormat("#.00");
    @BindView(R.id.tv_num)
    TextView tvNum;
    @BindView(R.id.tv_btn_et)
    TextView tvTopRightText;
    @BindView(R.id.rv_data)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.cb_all_select)
    CheckBox cbAllSelect;
    @BindView(R.id.tv_total_amount)
    TextView tvTotalAmount;
    @BindView(R.id.ll_price)
    LinearLayout llPrice;
    @BindView(R.id.sbtn_next)
    RoundTextView sbtnNext;

    private View notDataView;
    private boolean mIsDelete = true;
    private boolean mAllSelect;
    private double mTotalAmount = 0.00;


    List<CartListBean.ResultBean.DataBean> mList;
    ShopCartAdapter mAdapter;


    int signP = 1; //修改还是删除

    @Override
    protected CartListPresenter createPresenter() {
        return new CartListPresenter();
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_cart;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        mList = new ArrayList<>();
        LinearLayoutManager layoutManager3 = new LinearLayoutManager(getMe());
        layoutManager3.setOrientation(LinearLayoutManager.VERTICAL);
        layoutManager3.setSmoothScrollbarEnabled(true);
        layoutManager3.setAutoMeasureEnabled(true);
        recyclerView.setLayoutManager(layoutManager3);
        recyclerView.setNestedScrollingEnabled(false);
        //创建适配器
        mAdapter = new ShopCartAdapter(R.layout.item_shop_cart, mList);
        //给RecyclerView设置适配器
        recyclerView.setAdapter(mAdapter);
        notDataView = getLayoutInflater().inflate(R.layout.show_empty_view, (ViewGroup) recyclerView.getParent(), false);
        notDataView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                refreshLayout.autoRefresh();
            }
        });
        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                CartListBean.ResultBean.DataBean bean = mAdapter.getItem(position);
                switch (view.getId()) {
                    case R.id.img_btn_jian:
                        signP = 1;
                        int num = bean.getNum();
                        if (num > 1) {
                            num--;
                            mList.get(position).setNum(num);
                            mAdapter.notifyDataSetChanged();
                            mPresenter.onAddCartData(LoginHelper.getLonginData().getResult(), "up", num, String.valueOf(bean.getId()));
                        }
                        break;
                    case R.id.img_btn_jia:
                        signP = 1;
                        num = bean.getNum();
                        if (bean.getGood_num() > 0) {
                            if (num < bean.getGood_num()) {
                                num++;
                                mList.get(position).setNum(num);
                                mAdapter.notifyDataSetChanged();
                                mPresenter.onAddCartData(LoginHelper.getLonginData().getResult(), "up", num, String.valueOf(bean.getId()));
                            }
                        }
                        break;
                    case R.id.iv_product_select:
                        if (bean.isCheck()) {
                            mList.get(position).setCheck(false);
                            mAdapter.notifyDataSetChanged();
                        } else {
                            mList.get(position).setCheck(true);
                            mAdapter.notifyDataSetChanged();
                        }
                        NumAll();
                        break;
                }
            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
        pagehttp = 1;
        getListData();
    }

    @Override
    public void initRefreshLayout() {
        RefreshHelper.initRefreshLayout(refreshLayout, new CustomRefreshListener() {
            @Override
            public void _onRefresh(RefreshLayout refreshLayout) {
                pagehttp = 1;
                getListData();
            }

            @Override
            public void _onLoadMore(RefreshLayout refreshLayout) {
                pagehttp++;
                if (null != mList) {
                    getListData();
                }
            }
        });
    }

    private void getListData() {
        mPresenter.onCartListData(LoginHelper.getLonginData().getResult(), pagehttp, pageNum);
    }

    @Override
    public void onReLoggedIn(String msg) {

        RxToast.error(msg);
        LoginHelper.againGoToLoginActivity(getMe());
    }

    @Override
    public void onError(String msg) {
        RefreshHelper.finishRefresh(refreshLayout, pagehttp);
        RxToast.error(msg);
    }

    @Override
    public Context _getContext() {
        return getMe();
    }

    @Override
    public void onCartListSuccess(CartListBean bean) {
        RefreshHelper.finishRefresh(refreshLayout, pagehttp);
        tvNum.setText("共" + bean.getResult().getCount() + "件宝贝");
        cbAllSelect.setChecked(false);
        cbAllSelect.setButtonDrawable(R.drawable.check_false);
        if (pagehttp == 1) {
            tvTotalAmount.setText("0.00");
            if (bean.getResult() != null && bean.getResult().getData().size() > 0) {
                mAdapter.replaceData(bean.getResult().getData());
            } else {
                mAdapter.replaceData(bean.getResult().getData());
                mAdapter.setEmptyView(notDataView);
            }
        } else {
            if (bean.getResult() != null && bean.getResult().getData().size() > 0) {
                mAdapter.addData(bean.getResult().getData());
            }

        }
    }

    @Override
    public void onAddCartSuccess(MsgBean bean) {
        if (signP == 1)
            NumAll();
        else {
            RxToast.success(bean.getMsg());
            refreshLayout.autoRefresh();
        }
    }

    @Override
    public void onCheckCartSuccess(CartCheckBean bean) {
        tvNum.setText("共" + bean.getResult().getNum() + "件宝贝");
        tvTotalAmount.setText(String.valueOf(bean.getResult().getTotal_amount()));
    }

    @Override
    public void onOrderSuccess(OrderPlaceBean bean) {
        //提交訂單
        List<String> mIsGoods = new ArrayList<>();
        List<OrderSetBean> list = new ArrayList<>();
        for (int i = 0; i < mList.size(); i++) {
            if (mList.get(i).isCheck()) {
                mIsGoods.add(String.valueOf(mList.get(i).getId()));
                list.add(new OrderSetBean(mList.get(i).getGood_id(), mList.get(i).getImg(), mList.get(i).getTitle(), mList.get(i).getMoney(),
                        mList.get(i).getNum(), mList.get(i).getSpec_key(), mList.get(i).getPostage(), mList.get(i).getSpec_id(), ""));
            }
        }
        Bundle bundle = new Bundle();
        bundle.putSerializable("ListOrderSetBeans", (Serializable) list);
        bundle.putString("s_moneyAll", bean.getResult().getTotal_amount());
        bundle.putString("s_num", bean.getResult().getGood_num());
        bundle.putInt("sign", 2);
        bundle.putString("mIsGoods", StringUtil.convertListToString(mIsGoods));
        $startActivity(OrderConfirmActivity.class, bundle);
    }

    /**
     * 计算总价格
     */
    private void NumAll() {
        List<String> mIsGoods = new ArrayList<>();
        for (int i = 0; i < mList.size(); i++) {
            if (mList.get(i).isCheck()) {
                mIsGoods.add(String.valueOf(mList.get(i).getId()));
            }
        }
        if (mIsGoods.size() > 0) {
            mPresenter.onCheckCartData(LoginHelper.getLonginData().getResult(), StringUtil.convertListToString(mIsGoods))
            ;
        } else {
            tvTotalAmount.setText("0.00");
        }
    }

    @OnClick({R.id.ll_btn_left, R.id.ll_btn_right, R.id.cb_all_select, R.id.sbtn_next})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_btn_left:
                finish();
                break;
            case R.id.ll_btn_right:
                //todo 编辑
                if (mIsDelete) {
                    tvTopRightText.setText("完成");
                    sbtnNext.setText("删除");
                    llPrice.setVisibility(View.INVISIBLE);
                } else {
                    tvTopRightText.setText("管理");
                    sbtnNext.setText("结算");
                    llPrice.setVisibility(View.VISIBLE);
                }
                mIsDelete = !mIsDelete;
                break;
            case R.id.cb_all_select:
                if (mAllSelect) {
                    mAllSelect = false;
                    for (int i = 0; i < mList.size(); i++) {
                        mList.get(i).setCheck(false);
                    }
                    mTotalAmount = 0.00;
                } else {
                    mAllSelect = true;
                    mTotalAmount = 0.00;
                    for (int i = 0; i < mList.size(); i++) {
                        mList.get(i).setCheck(true);
                    }
                }
                cbAllSelect.setChecked(mAllSelect);
                if (mAllSelect)
                    cbAllSelect.setButtonDrawable(R.drawable.check_true);
                else cbAllSelect.setButtonDrawable(R.drawable.check_false);
                mAdapter.notifyDataSetChanged();
                NumAll();

                break;
            case R.id.sbtn_next:
                if (mIsDelete) {
                    //todo 结算
                    List<String> mIsGoods = new ArrayList<>();
                    for (int i = 0; i < mList.size(); i++) {
                        if (mList.get(i).isCheck()) {
                            mIsGoods.add(String.valueOf(mList.get(i).getId()));
                        }
                    }
                    if (mIsGoods.size() > 0) {
                        //todo 结算 下单
                        LoggerUtils.e("結算选择的商品id有：" + StringUtil.convertListToString(mIsGoods));
                        mPresenter.onOrderData(LoginHelper.getLonginData().getResult(),
                                "cart", StringUtil.convertListToString(mIsGoods));

                    } else
                        RxToast.error("请选择商品");
                } else {
                    //todo 删除
                    List<String> mIsGoods = new ArrayList<>();
                    for (int i = 0; i < mList.size(); i++) {
                        if (mList.get(i).isCheck()) {
                            mIsGoods.add(String.valueOf(mList.get(i).getId()));
                        }
                    }
                    if (mIsGoods.size() > 0) {
                        SelectDialog.show(getMe(), getResources().getString(R.string.tips_str), getResources().getString(R.string.tips_delete_list_str), getResources().getString(R.string.main_sure), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                //todo 删除
//                                upDeleteCartData(mIsGoods);
                                signP = 2;
                                mPresenter.onAddCartData(LoginHelper.getLonginData().getResult(), "del", 0, StringUtil.convertListToString(mIsGoods));

                            }
                        }, getResources().getString(R.string.main_cancel), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        });
                    } else
                        RxToast.error("请选择商品");
                }
                break;
        }
    }


    class ShopCartAdapter extends BaseQuickAdapter<CartListBean.ResultBean.DataBean, BaseViewHolder> {
        public ShopCartAdapter(int layoutResId, @Nullable List<CartListBean.ResultBean.DataBean> data) {
            super(layoutResId, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, final CartListBean.ResultBean.DataBean item) {
            helper.addOnClickListener(R.id.img_btn_jia);
            helper.addOnClickListener(R.id.img_btn_jian);

            GlideUtil.ImageLoad(this.mContext, item.getImg(), helper.getView(R.id.img));
            helper.setText(R.id.tv_title, item.getTitle())
                    .setText(R.id.tv_spec_key, item.getSpec_key())
                    .setText(R.id.tv_money, item.getMoney())
                    .setText(R.id.tv_num, String.valueOf(item.getNum()));


            helper.addOnClickListener(R.id.iv_product_select);
            ImageView ivProductSelect = helper.getView(R.id.iv_product_select);
            if (item.isCheck())
                ivProductSelect.setImageResource(R.drawable.check_true);
            else
                ivProductSelect.setImageResource(R.drawable.check_false);

        }

    }
}
